<template>
  <div class="canvas">
    <div class="canvas-wrapper flex">
      <div class="sign-canvas common-canvas flex-column m-20">
        <p class="title">Signature</p>
        <canvas
          ref="signatureCanvas"
          class="signature-canvas"
          width="500"
          height="375"
          @mousedown="signatureMouseDown"
        ></canvas>
        <div class="operate flex">
          <a-button type="primary" @click="createImg">生成图片</a-button>
          <a-button type="default" @click="clearSign">清除签名</a-button>
        </div>
      </div>

      <div class="color-pick-canvas common-canvas flex-column m-20">
        <p class="title">Color Picker</p>
        <canvas
          ref="colorPickerCanvas"
          class="color-picker-canvas"
          width="500"
          height="375"
          @mousemove="colorPickerMouseMove"
          @mouseleave="currentColor = null"
        ></canvas>
        <div
          class="operate flex"
          :style="{
            padding: '8px',
            color: '#fff',
            backgroundColor: currentColor || 'transparent',
          }"
        >
          鼠标划过颜色：{{ currentColor }}
        </div>
      </div>

      <div class="drag-canvas common-canvas flex-column m-20">
        <p class="title">Drag Image</p>
        <canvas
          ref="dragCanvas"
          class="drag-canvas"
          width="500"
          height="375"
          @mousedown="dragMouseDown"
        ></canvas>
        <div class="operate flex">
          <a-button>占位按钮</a-button>
        </div>
      </div>

      <div class="curettage-canvas common-canvas flex-column m-20">
        <p class="title">Curettage</p>
        <canvas
          ref="curettageCanvas"
          class="curettage-canvas"
          width="500"
          height="375"
          @mousedown="handleMouseDown"
        ></canvas>
        <div class="operate flex">
          <a-button @click="reset">Restart</a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { message } from "ant-design-vue";

import bg from "../../../assets/images/bg.jpeg";
import relax from "../../../assets/images/relax.png";
import loginForm from "../../../assets/images/login-form.png";
import summary from "../../../assets/images/summary.png";
import top from "../../../assets/images/top.png";

const signatureCanvas = ref(null);

function signatureMouseDown(e) {
  console.log(signatureCanvas.value.width, "===");
  const ctx = signatureCanvas.value.getContext("2d");
  ctx.beginPath();
  ctx.moveTo(e.offsetX, e.offsetY);
  signatureCanvas.value.addEventListener("mousemove", signatureMouseMove);
  signatureCanvas.value.addEventListener("mouseup", signatureMouseUp);
}

function signatureMouseMove(e) {
  console.log(e, "===");
  const ctx = signatureCanvas.value.getContext("2d");
  ctx.lineTo(e.offsetX, e.offsetY);
  ctx.stroke();
}
function signatureMouseUp(e) {
  const ctx = signatureCanvas.value.getContext("2d");
  ctx.closePath();
  signatureCanvas.value.removeEventListener("mousemove", signatureMouseMove);
}

async function createImg() {
  console.log(signatureCanvas.value, "===23");
  let url = signatureCanvas.value.toDataURL("image/png");
  console.log(url, "===url");
  try {
    await navigator.clipboard.writeText(url);
    message.success("图片url已复制到剪切板");
  } catch (err) {
    console.log(err, "====");
    message.error("复制失败，请手动复制");
  }
}

function clearSign() {
  const ctx = signatureCanvas.value.getContext("2d");
  ctx.clearRect(
    0,
    0,
    signatureCanvas.value.width,
    signatureCanvas.value.height
  );
}

const colorPickerCanvas = ref(null);

onMounted(() => {
  colorPickerDraw();
  drawImage();
  drawCurettageCanvas();
});

let currentColor = ref(null);
function colorPickerDraw() {
  const ctx = colorPickerCanvas.value.getContext("2d");
  const image = new Image();
  image.src = bg;
  image.onload = () => {
    ctx.drawImage(image, 0, 0, 500, 375);
  };
}

function colorPickerMouseMove(e) {
  const ctx = colorPickerCanvas.value.getContext("2d");
  let imageData = ctx.getImageData(e.offsetX, e.offsetY, 1, 1).data;
  currentColor.value = `rgba(${imageData[0]},${imageData[1]},${imageData[2]},${
    imageData[3] / 255
  })`;
}

const dragCanvas = ref(null);
let imgList = ref([top, relax, loginForm, summary]);
const imageData = ref([]);
const currentPoint = ref({ x: 0, y: 0 });
const currentIndex = ref(null);

function drawImageItem(obj) {
  const ctx = dragCanvas.value.getContext("2d");
  ctx.drawImage(obj.img, obj.x, obj.y, obj.w, obj.h);
  ctx.beginPath();
  ctx.strokeStyle = "#fff";
  // TODO: 这里使用strokeRect,下面的isPointInPath就会不生效
  ctx.rect(obj.x, obj.y, obj.w, obj.h);
  ctx.stroke();
  ctx.closePath();
}
function drawImage() {
  imgList.value.forEach((imgSrc) => {
    let img = new Image();
    img.src = imgSrc;
    let w = 100,
      h = 75,
      x = Math.random() * 400,
      y = Math.random() * 275;
    const obj = {
      img,
      x,
      y,
      w,
      h,
    };
    img.onload = () => {
      drawImageItem(obj);
    };
    imageData.value.push(obj);
  });
}

function dragMouseDown(e) {
  currentPoint.value.x = e.offsetX;
  currentPoint.value.y = e.offsetY;
  console.log(currentPoint.value);
  imageData.value.forEach((item, index) => {
    drawImageItem(item);
    checkImage(index);
    if (currentIndex.value === null) return;
    dragCanvas.value.addEventListener("mousemove", dragMouseMove);
    dragCanvas.value.addEventListener("mouseup", dragMouseUp);
  });
}

function checkImage(index) {
  const ctx = dragCanvas.value.getContext("2d");
  if (ctx.isPointInPath(currentPoint.value.x, currentPoint.value.y)) {
    currentIndex.value = index;
    console.log("当前选中图片索引：", currentIndex.value);
  }
}

function dragMouseMove(e) {
  const ctx = dragCanvas.value.getContext("2d");
  const moveX = e.offsetX;
  const moveY = e.offsetY;
  ctx.clearRect(0, 0, 500, 375);
  imageData.value[currentIndex.value].x += moveX - currentPoint.value.x;
  imageData.value[currentIndex.value].y += moveY - currentPoint.value.y;
  currentPoint.value.x = moveX;
  currentPoint.value.y = moveY;
  imageData.value.forEach((item) => drawImageItem(item));
}

function dragMouseUp() {
  dragCanvas.value.removeEventListener("mousemove", dragMouseMove);
  dragCanvas.value.removeEventListener("mouseup", dragMouseUp);
  currentIndex.value = null;
}

const curettageCanvas = ref(null);

function drawCurettageCanvas() {
  const ctx = curettageCanvas.value.getContext("2d");
  console.log(ctx, "===");
  let image = new Image();
  image.src = loginForm;
  image.onload = () => {
    ctx.drawImage(image, 0, 0, 500, 375);
    ctx.stroke();
  };
}

let ratio = ref(0);
let textExistFlag = ref(false);
const targetColor = [204, 204, 204];

function handleMouseDown(e) {
  console.log(e);
  let ctx = curettageCanvas.value.getContext("2d");
  ctx.globalCompositeOperation = "source-over";
  ctx.strokeStyle = "#ccc";
  ctx.lineWidth = 50;
  ctx.lineCap = "round";
  ctx.lineJoin = "round";
  if (!textExistFlag.value) {
    ctx.beginPath();
    ctx.moveTo(e.offsetX, e.offsetY);
    curettageCanvas.value.addEventListener("mousemove", handleMouseMove);
    curettageCanvas.value.addEventListener("mouseup", handleMouseUp);
  }
}

function handleMouseMove(e) {
  let ctx = curettageCanvas.value.getContext("2d");
  const imageData = ctx.getImageData(0, 0, 500, 375).data;
  let count = 0;
  for (let i = 0; i < imageData.length; i += 4) {
    var red = imageData[i];
    var green = imageData[i + 1];
    var blue = imageData[i + 2];
    var alpha = imageData[i + 3];
    if (
      red === targetColor[0] &&
      green === targetColor[1] &&
      blue === targetColor[2]
    ) {
      count++;
    }
  }
  ratio.value = count / (500 * 375);
  ctx.lineTo(e.offsetX, e.offsetY);
  ctx.stroke();
}
function handleMouseUp(e) {
  let ctx = curettageCanvas.value.getContext("2d");
  ctx.closePath();
  console.log(textExistFlag.value, ratio.value, "==");
  if (!textExistFlag.value && ratio.value > 0.5) {
    ctx.globalCompositeOperation = "copy";
    ctx.fillStyle = `rgba${(255, 255, 255, ratio.value)}`;
    ctx.font = "200px SimSun, Songti SC";
    ctx.beginPath();
    ctx.fillText(Math.floor(Math.random() * 20), 200, 187);
    ctx.closePath();
    textExistFlag.value = true;
  }
  curettageCanvas.value.removeEventListener("mousedown", handleMouseDown);
  curettageCanvas.value.removeEventListener("mousemove", handleMouseMove);
  curettageCanvas.value.removeEventListener("mouseup", handleMouseUp);
}

function reset() {
  textExistFlag.value = false;
  ratio.value = 0;
  const ctx = curettageCanvas.value.getContext("2d");
  ctx.clearRect(0, 0, 500, 375);
  drawCurettageCanvas();
}
</script>

<style scoped lang="less">
@drag-color: rgba(255, 192, 203, 0.8);
@sign-color: rgba(173, 216, 230, 0.8);
@snake-color: rgba(144, 238, 144, 0.4);
@font-color: rgba(255, 255, 255, 0.7);
@curettage-color: rgba(224, 245, 133, 0.7);

.canvas {
  height: 100%;

  &-wrapper {
    height: 100%;
    flex-wrap: wrap;
    justify-content: center;

    .common-canvas {
      width: 500px;
      height: 500px;
      text-align: center;
      border-radius: 8px;

      canvas {
        flex: 1;
      }

      .title {
        border-bottom: 1px solid #fff;
        font-size: 16px;
        padding-bottom: 8px;
      }

      .operate {
        width: 100%;
        border-top: 1px solid #fff;
        padding-top: 8px;

        .ant-btn {
          flex: 1;
        }
      }
    }

    .sign-canvas {
      background-color: @sign-color;
      box-shadow: 5px 5px 10px @sign-color;

      border: 1px solid @sign-color;
    }

    .color-pick-canvas {
      box-shadow: 5px 5px 10px @sign-color;
      border: 1px solid @sign-color;
      background-color: #eee;
    }

    .drag-canvas {
      background-color: @drag-color;
      box-shadow: 5px 5px 10px @drag-color;
      border: 1px solid @drag-color;
    }

    .curettage-canvas {
      background-color: @curettage-color;
      box-shadow: 5px 5px 10px @curettage-color;
      border: 1px solid @curettage-color;
    }
  }
}
</style>
